package com.mcbbs.web.util;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Component
@PropertySource(value = "classpath:application.properties",encoding = "utf-8")
public class SendEmail {
//    从配置文件中获取相应的值
    @Value("${email.hostName}")
    private String host;
    @Value("${email.username}")
    private String username;
    @Value("${email.password}")
    private String password;
    @Value("${email.sslport}")
    private String sslport;
    @Value("${email.name}" )
    private String name;
    @Value("${email.charset}")
    private String charset;

    private HtmlEmail htmlEmail;

//    初始化邮箱服务器配置
    @PostConstruct
    public void init(){
        try {
            htmlEmail = new HtmlEmail();
            htmlEmail.setCharset(charset);
            htmlEmail.setSslSmtpPort(sslport);
            htmlEmail.setHostName(host);
            htmlEmail.setFrom(username,name);
            htmlEmail.setAuthentication(username,password);
        } catch (EmailException e) {
            System.out.println("邮箱服务器配置失败，请检查您填写的账号");
            e.printStackTrace();
        }
    }

    public boolean sendEmail(String msg,String email,String title){
        try {
            init();
            htmlEmail.setSubject(title);
            htmlEmail.addTo(email);
            htmlEmail.setMsg(msg);
            String send = htmlEmail.send();
            return true;
        } catch (EmailException e) {
            e.printStackTrace();
            return false;
        }finally {

        }
    }
//    发送注册验证邮件
    public boolean sendRegEmail(String email,String code){
        String msg = "<h1>欢迎您注册我们的游戏账号</h1><p>您的验证码是:<span color=red><b>"+code+"</b></span></p><p>该验证码五分钟之内有效，如果不是您操作的,请无视该邮件，如果对您有骚扰请联系：xxxxx</p>";
        String title = "我的世界服务器账号注册，验证邮箱";
        return sendEmail(msg,email,title);
    }
//绑定邮箱
    public boolean sendBinDingEmail(String email,String code){
        String msg = "<h1>绑定邮箱</h1><p>您的验证码是:<span color=red><b>"+code+"</b></span></p><p>该验证码五分钟之内有效，如果不是您操作的,请无视该邮件，如果对您有骚扰请联系：xxxxx</p>";
        String title = "我的世界服务器邮箱绑定，验证邮箱";
        return sendEmail(msg,email,title);
    }


}
